﻿using CPAIS.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;

namespace CPAIS.Web.AjaxHandlers
{
    public class UploadFileHandler : AjaxHandler
    {
        public UploadFileHandler(HttpContext context) : base(context) { }

        /// <summary>
        /// Ajax Request: 
        ///     UploadFile
        /// Params:
        ///     chunk, chunks, name...
        /// Reponse:
        ///     Plain text
        /// </summary>
        #region Ajax Request UploadFile
        
        public void UploadFile()
        {
            // Gets path name that the uploaded file saves.
            string root = DSMgr.RootOfOriginalEventLogs;
            if (!Directory.Exists(root))
                Directory.CreateDirectory(root);
            string name = Params[Constants.Name];
            string pathName = Path.Combine(root, name);

            // Opens a file, if our chunk is 1 or more, we should be appending to an existing
            // file, otherwise create a new file.
            int chunk = Params[Constants.Chunk] != null ? int.Parse(Params[Constants.Chunk]) : 0;
            int chunks = Params[Constants.Chunks] != null ? int.Parse(Params[Constants.Chunks]) : 0;

            if (chunk == 0 && File.Exists(pathName))
                File.Delete(pathName);

            FileStream fs = new FileStream(pathName, chunk == 0 ? FileMode.Create : FileMode.Append);

            // Writes input stream to a buffer.
            Byte[] buffer = null;
            if (Request.ContentType == "application/octet-stream" && Request.ContentLength > 0)
            {
                buffer = new Byte[Request.InputStream.Length];
                Request.InputStream.Read(buffer, 0, buffer.Length);
            }
            else if (Request.ContentType.Contains("multipart/form-data") &&
                Request.Files.Count > 0 &&
                Request.Files[0].ContentLength > 0)
            {
                buffer = new Byte[Request.Files[0].InputStream.Length];
                Request.Files[0].InputStream.Read(buffer, 0, buffer.Length);
            }

            // Writes the buffer to a file.
            fs.Write(buffer, 0, buffer.Length);
            fs.Flush();
            fs.Close();

            // Loads and Saves the log file to database.
            if (chunk == chunks - 1)
            {
                LogModel logModel = null;
                try
                {
                    logModel = DSMgr.LPFactory.ParseLog(pathName, null);
                }
                catch (Exception)
                {
                    WriteText("Failed");
                    File.Delete(pathName);
                    return;
                }
                WriteText("Success");
                Thread thread = new Thread(new ParameterizedThreadStart(SavingLogToDBThreadProc));
                thread.Start(logModel);
            }
            else
            {
                // Writes success.
                WriteText("Success");
            }
        }

        private void SavingLogToDBThreadProc(object state)
        {
            LogModel logModel = state as LogModel;                        
            DSMgr.SaveLogModel(logModel);
        }

        #endregion
    }
}